"""
查询缓存服务
为通用数据库查询提供缓存功能
"""

import hashlib
import json
from typing import Dict, Any, Optional, Union
from src.services.cache_service import CacheService
from src.config.settings import settings
from src.utils.logging import get_logger

logger = get_logger(__name__)


class QueryCacheService:
    """查询缓存服务类"""
    
    def __init__(self, cache_dir: Optional[str] = None):
        """
        初始化查询缓存服务
        
        Args:
            cache_dir: 缓存目录路径
        """
        cache_dir = cache_dir or f"{settings.CACHE_DIR}/queries"
        self.cache_service = CacheService(cache_dir=cache_dir)
        self.hits = 0
        self.misses = 0
        
        logger.info(f"查询缓存服务初始化完成，目录: {cache_dir}")
    
    def _generate_cache_key(self, table_name: str, query_params: Dict[str, Any]) -> str:
        """
        生成查询缓存键
        
        Args:
            table_name: 表名
            query_params: 查询参数
            
        Returns:
            缓存键
        """
        # 创建包含表名和查询参数的字符串
        key_data = {
            "table": table_name,
            "params": query_params
        }
        
        # 转换为JSON字符串并生成MD5哈希作为缓存键
        key_string = json.dumps(key_data, sort_keys=True, default=str)
        return hashlib.md5(key_string.encode('utf-8')).hexdigest()
    
    def get_query_result(self, table_name: str, query_params: Dict[str, Any]) -> Optional[Any]:
        """
        获取查询结果缓存
        
        Args:
            table_name: 表名
            query_params: 查询参数
            
        Returns:
            缓存的查询结果或None
        """
        cache_key = self._generate_cache_key(table_name, query_params)
        cached_result: Optional[Any] = self.cache_service.get(cache_key)
        
        if cached_result is not None:
            self.hits += 1
            logger.debug(f"查询缓存命中: 表 {table_name}")
            return cached_result
        else:
            self.misses += 1
            logger.debug(f"查询缓存未命中: 表 {table_name}")
            return None
    
    def set_query_result(self, table_name: str, query_params: Dict[str, Any], 
                        result: Any, ttl: int = 1800):
        """
        缓存查询结果
        
        Args:
            table_name: 表名
            query_params: 查询参数
            result: 查询结果
            ttl: 缓存过期时间（秒），默认30分钟
        """
        cache_key = self._generate_cache_key(table_name, query_params)
        success = self.cache_service.set(cache_key, result, ttl)
        
        if success:
            logger.debug(f"查询结果已缓存: 表 {table_name}")
        else:
            logger.warning(f"查询结果缓存失败: 表 {table_name}")
    
    def invalidate_table_cache(self, table_name: str):
        """
        使指定表的所有缓存失效
        
        Args:
            table_name: 表名
        """
        # 注意：由于当前缓存实现的限制，我们无法精确地只删除特定表的缓存
        # 这里我们清理所有查询缓存
        cleared_count = self.cache_service.clear()
        logger.info(f"清理了 {cleared_count} 个查询缓存项")
    
    def get_stats(self) -> Dict[str, Any]:
        """
        获取缓存统计信息
        
        Returns:
            统计信息字典
        """
        total_requests = self.hits + self.misses
        hit_rate = (self.hits / total_requests) if total_requests > 0 else 0
        
        base_stats = self.cache_service.get_stats()
        
        return {
            "hits": self.hits,
            "misses": self.misses,
            "hit_rate": hit_rate,
            "total_requests": total_requests,
            "base_cache_stats": base_stats
        }
    
    def clear_stats(self):
        """清空统计信息"""
        self.hits = 0
        self.misses = 0
    
    def health_check(self) -> bool:
        """
        检查缓存服务健康状态
        
        Returns:
            是否健康
        """
        return self.cache_service.health_check()


# 全局查询缓存实例
query_cache_service = QueryCacheService()